var nextGreaterElements = function(nums) {
  const stack = [];
  const res = [];
  const len = nums.length;
  const newNums = nums.concat(nums);

  for (let i = 2 * len - 1; i >= 0; i--) {
    let num = newNums[i];
    while (stack.length && num >= newNums[stack[stack.length - 1]]) {
      stack.pop();
    }
    if (stack.length) {
      res[i] = newNums[stack[stack.length - 1]];
    } else {
      res[i] = -1;
    }
    stack.push(i);
  }

  return res.slice(0, len);
};

const nums = [1,2,3,4,3];
console.log(nextGreaterElements(nums)); // [2,3,4,-1,4]